package cn.lopr.mvc.frame.processors;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.text.SimpleDateFormat;
import java.util.TimeZone;

public class RetValProcess extends Processor {

    public final ObjectMapper mapper;

    public RetValProcess() {
        mapper = new ObjectMapper();
        mapper.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        mapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);
        mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
    }

    public Object processRetVal(Object retVal, Class<?> paramType) {

        if (super.isCompatibleType(retVal, paramType)) {
            return retVal;
        }

        String jsonVal = "";

        try {
            jsonVal = mapper.writeValueAsString(retVal);

        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }

        return jsonVal;
    }

    public String processErrorMessage(Throwable cause) {
        StringBuilder sb = new StringBuilder();
        sb.append(cause.getMessage()).append("\t");

        for (StackTraceElement stackTraceElement : cause.getStackTrace()) {
            sb.append("<p>").append("\t\t").append(stackTraceElement.toString()).append("</p>");
        }

        return sb.toString();
    }
}
